#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Float, Integer, Boolean, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""sight_desc_title collection has
    descid:        景点描述id (int)
    title:         景点描述标题 (str)
    imgid:         景点描述小图标(int)
    imgurl:        景点描述小图标urll(str)
"""


class SightDescTitleItem(object):
    """docstring for SightDescTitleItem"""

    def to_dict(self):
        res = {}
        res['descid'] = self.descid
        res['title'] = self.title
        res['imgid'] = self.imgid
        res['imgurl'] = self.imgurl
        return res

    def __repr__(self):
        print "%d : %s" % (self.descid, self.title)


sight_desc_title_table = Table(
    'sight_desc_title', metadata,
    Column('id', Integer, primary_key=True),
    Column('descid', Integer, index=True, unique=True, nullable=False),
    Column('title', Unicode(28), nullable=False),
    Column('imgid', Integer, default=0, nullable=False),
    Column('imgurl', Unicode(150), default='', nullable=False)
)

mapper(SightDescTitleItem, sight_desc_title_table)


def create_sight_desc_title_table_if_not_exist():
    metadata.create_all(engine)


def add_sight_desc_title_item(p_item):
    item = SightDescTitleItem()
    item.descid = p_item['descid']
    item.title = p_item['title']
    item.imgid = p_item['imgid']
    item.imgurl = p_item['imgurl']
    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True

    except Exception, e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_sight_desc_title_all():
    try:
        session = Session()
        items = session.query(SightDescTitleItem).filter_by().order_by(SightDescTitleItem.descid.asc()).all()
        res = []
        for item in items:
            res.append(item.to_dict())
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
p_descid
p_title
'''


def update_title_by_descid(p_descid, p_item):
    if not (p_descid and p_item):
        return False
    try:
        updateField = {}
        if 'title' in p_item:
            updateField[SightDescTitleItem.title] = p_item['title']
        if 'imgid' in p_item:
            updateField[SightDescTitleItem.imgid] = p_item['imgid']
        if 'imgurl' in p_item:
            updateField[SightDescTitleItem.imgurl] = p_item['imgurl']

        if not updateField:
            return False
        session = Session()
        session.query(SightDescTitleItem).filter(SightDescTitleItem.descid == p_descid).update(updateField,
                                                                                               synchronize_session=False)
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_sight_desc_title_by_descid(p_descid):
    try:
        session = Session()
        item = session.query(SightDescTitleItem).filter(SightDescTitleItem.descid == p_descid).first()
        res = item.to_dict() if item else None
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


def delete_title_by_descid(p_descid):
    try:
        session = Session()
        session.query(SightDescTitleItem).filter(SightDescTitleItem.descid == p_descid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


if __name__ == "__main__":
    create_sight_desc_title_table_if_not_exist()
    '''
    item1 = {'descid': 1, 'title': '最美季节'}
    item2 = {'descid': 2, 'title': '开放时间'}
    item3 = {'descid': 3, 'title': '游览时间'}
    item4 = {'descid': 4, 'title': '主要看点'}
    item5 = {'descid': 5, 'title': '大家印象'}
    item6 = {'descid': 6, 'title': '推荐理由'}
    item7 = {'descid': 7, 'title': '门票价格'}
    item8 = {'descid': 8, 'title': '测试'}
    add_sight_desc_title_item(item1)
    add_sight_desc_title_item(item2)
    add_sight_desc_title_item(item3)
    add_sight_desc_title_item(item4)
    add_sight_desc_title_item(item5)
    add_sight_desc_title_item(item6)
    add_sight_desc_title_item(item7)
    add_sight_desc_title_item(item8)

    res = get_sight_desc_title_all()
    print res
    
    update_title_by_descid( 8, '测试修改')
    res = get_sight_desc_title_all()
    print res
    
    delete_title_by_descid( 8 )
    res = get_sight_desc_title_all()
    print res
    '''
